/*
 * Copyright 2010 Original Author(s)
 * 
 * This file is part of Kommando
 * 
 * Kommando is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Kommando is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Kommando.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.kommando.textfile.objectsource;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import org.kommando.core.util.Assert;

/**
 * Abstraction of a text file.
 * 
 * @author Peter De Bruycker
 */
public class TextFileObject {

    private TextLines lines;
    private File file;

    public TextFileObject(File file) {
        Assert.argumentNotNull("file", file);

        this.file = file;
    }

    public void save() throws IOException {
        if (lines == null) {
            // not yet read, so don't write
            return;
        }

        FileWriter writer = new FileWriter(file);
        lines.writeTo(writer);
        writer.close();
    }

    public void reset() throws IOException {
        lines = new TextLines();

        FileReader reader = new FileReader(file);
        lines.readFrom(reader);
        reader.close();
    }

    public TextLines getLines() throws IOException {
        if (lines == null) {
            reset();
        }

        return lines;
    }

    public void appendText(String text) throws IOException {
        getLines().appendText(text);
    }

    public void prependText(String text) throws IOException {
        getLines().prependText(text);
    }

}
